package global

import (
	"air_chat/common/config"
	"context"
	"fmt"

	"github.com/go-redis/redis/v8"
)

var REDIS = InitRedis()

func InitRedis() *redis.Client {
	host := config.Conf.REDIS.Host
	port := config.Conf.REDIS.Port
	pass := config.Conf.REDIS.Pass
	dbname := config.Conf.REDIS.DbName

	dsn := fmt.Sprintf("%s:%s", host, port)
	client := redis.NewClient(&redis.Options{
		Addr:     dsn,
		Password: pass,   // no password set
		DB:       dbname, // use default DB
	})

	_, err := client.Ping(context.Background()).Result()
	if err != nil {
		ZAPLOGGER.Sugar().Errorf("redis Init Error %s", err)
	}

	return client
}

const (
	// 缓存前缀
	PublishKey = "websocket"
)

// 编写 Publish 方法发布消息到redis
func Publish(ctx context.Context, channel string, msg string) error {
	var err error
	// fmt.Println("redis publish, channel: ", channel, "msg: ", msg)
	err = REDIS.Publish(ctx, channel, msg).Err()
	return err

}

// 编写 Subscribe 方法订阅消息
func Subscribe(ctx context.Context, channel string) (string, error) {
	sub := REDIS.Subscribe(ctx, channel)
	msg, err := sub.ReceiveMessage(ctx)
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	// fmt.Println("redis subscribe, channel: ", channel, "msg: ", msg.Payload)
	return msg.Payload, err
}
